<template>
  <div class="container">
    <div class="app-container">
      <div class="role-operate">
        <el-button
          size="mini"
          type="primary"
          @click="showDialog = true"
        >添加角色</el-button>
      </div>
      <!-- 放置table组件 -->
      <el-table :data="roleList">
        <el-table-column prop="name" align="center" width="200" label="角色">
          <template v-slot="{ row }">
            <el-input
              v-if="row.isEdit"
              v-model="row.editRow.name"
              size="mini"
            />
            <span v-else>{{ row.name }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="state" align="center" width="200" label="启用">
          <template v-slot="{ row }">
            <el-switch
              v-if="row.isEdit"
              v-model="row.editRow.state"
              :active-value="1"
              :inactive-value="0"
            />
            <span v-else>
              {{
                row.state === 1 ? "已启用" : row.state === 0 ? "未启用" : "无"
              }}
            </span>
          </template>
        </el-table-column>
        <el-table-column prop="description" align="center" label="描述">
          <template v-slot="{ row }">
            <el-input
              v-if="row.isEdit"
              v-model="row.editRow.description"
              type="textarea"
            />
            <span v-else>{{ row.description }}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="操作">
          <template v-slot="{ row }">
            <template v-if="row.isEdit">
              <!-- 编辑状态 -->
              <el-button
                type="primary"
                size="mini"
                @click="btnEditOK(row)"
              >确定</el-button>
              <el-button
                size="mini"
                @click="btnEditChancel(row)"
              >取消</el-button>
            </template>
            <template v-else>
              <!-- 非编辑状态 -->
              <el-button
                size="mini"
                type="text"
                @click="btnPermission(row.id)"
              >分配权限</el-button>
              <el-button
                size="mini"
                type="text"
                @click="btnEditRow(row)"
              >编辑</el-button>
              <el-popconfirm
                title="这是一段内容确定删除吗？"
                confirm-button-text="好的"
                cancel-button-text="不用了"
                icon="el-icon-info"
                icon-color="red"
                @onConfirm="handleConfirm(row.id)"
              >
                <el-button
                  id="delete"
                  slot="reference"
                  size="mini"
                  type="text"
                >删除</el-button>
              </el-popconfirm>
            </template>
          </template>
        </el-table-column>
      </el-table>
      <el-row type="flex" style="height: 60px" align="middle" justify="end">
        <!-- 放置分页组件 -->
        <el-pagination
          layout="prev, pager, next"
          :total="pageParams.total"
          :page-size="pageParams.pagesize"
          :current-page="pageParams.page"
          @current-change="changePage"
        />
      </el-row>
    </div>
    <!-- dialog弹层（新增角色） -->
    <el-dialog
      :close-on-click-modal="false"
      width="500px"
      title="新增角色"
      :visible.sync="showDialog"
      @close="btnCancel"
    >
      <el-form ref="form" label-width="120px" :model="roleForm" :rules="rules">
        <el-form-item label="角色名称" prop="name">
          <el-input v-model="roleForm.name" style="width: 300px" size="mini" />
        </el-form-item>
        <el-form-item label="启用">
          <el-switch v-model="roleForm.state" size="mini" />
        </el-form-item>
        <el-form-item prop="description" label="角色描述">
          <el-input
            v-model="roleForm.description"
            type="textarea"
            :rows="3"
            style="width: 300px"
            size="mini"
          />
        </el-form-item>
        <el-form-item>
          <el-row type="flex" justify="center">
            <el-col :span="12">
              <el-button
                type="primary"
                size="mini"
                @click="submitOk"
              >确定</el-button>
              <el-button size="mini" @click="btnCancel">取消</el-button>
            </el-col>
          </el-row>
        </el-form-item>
      </el-form>
    </el-dialog>
    <!-- 分配权限 dialog弹层 -->
    <el-dialog
      :close-on-click-modal="false"
      title="分配权限"
      :visible.sync="showPermissionDialog"
    >
      <el-tree
        ref="permTree"
        node-key="id"
        :data="permissionData"
        :props="{ label: 'name' }"
        show-checkbox
        default-expand-all
        :default-checked-keys="permIds"
      />
      <el-row slot="footer" type="flex" justify="center">
        <el-col :span="6">
          <el-button
            type="primary"
            size="mini"
            @click="btnPermissionOK"
          >确定</el-button>
          <el-button
            size="mini"
            @click="showPermissionDialog = false"
          >取消</el-button>
        </el-col>
      </el-row>
    </el-dialog>
  </div>
</template>

<script>
import {
  getRoleList,
  addRole,
  updateRole,
  delRole,
  getRoleDetail,
  assignPerm
} from '@/api/role'
import { getPermissionList } from '@/api/permission'
import { dataConvertion } from '@/utils'

export default {
  name: 'Role',
  data() {
    return {
      // 放置分页组件的数据
      roleList: [],
      // 分页信息
      pageParams: {
        page: 1, // 第几页
        pagesize: 5, // 每页多少条
        total: 0
      },
      showDialog: false,
      roleForm: {
        name: '',
        description: '',
        state: 0 // 默认未1启用 关闭 0 打开1
      },
      rules: {
        name: [
          { required: true, message: '角色名称不能为空', trigger: 'blur' }
        ],
        description: [
          { required: true, message: '角色描述不能为空', trigger: 'blur' }
        ]
      },
      showPermissionDialog: false,
      permissionData: [],
      currentRoleId: null,
      permIds: []
    }
  },
  created() {
    this.getRoleList()
  },
  methods: {
    // 获取角色列表
    async getRoleList() {
      const { rows, total } = await getRoleList(this.pageParams)
      this.roleList = rows // 赋值数据
      // item.isEdit = false // 添加一个属性 初始值为false
      // 数据响应式的问题  数据变化 视图更新
      // 添加的动态属性 不具备响应式特点
      // this.$set(目标对象, 属性名称, 初始值) 可以针对目标对象 添加的属性 添加响应式
      this.roleList.forEach((item) => {
        this.$set(item, 'isEdit', false)
        this.$set(item, 'editRow', {
          name: item.name,
          state: item.state,
          description: item.description
        })
      })
      this.pageParams.total = total
    },
    // 改变页码 newPage 新的页码
    changePage(newPage) {
      this.pageParams.page = newPage
      this.getRoleList()
    },
    // 新增角色 - 点击确认按钮
    submitOk() {
      this.$refs.form.validate((isok) => {
        if (isok) {
          addRole(this.roleForm).then((res) => {
            this.$message.success('添加成功')
            this.getRoleList()
            this.btnCancel()
          })
        }
      })
    },
    // 新增角色 - 点击取消按钮
    btnCancel() {
      this.roleForm = {
        name: '',
        description: '',
        state: 0
      }
      this.$refs.form.resetFields() // 重置表单数据
      this.showDialog = false
    },
    // 点击编辑按钮 进入行内编辑模式
    btnEditRow(row) {
      row.isEdit = true
      // 更新缓存数据
      row.editRow.name = row.name
      row.editRow.state = row.state
      row.editRow.description = row.description
    },
    // 编辑模式下 - 点击确认按钮
    async btnEditOK(row) {
      if (row.editRow.name && row.editRow.description) {
        try {
          await updateRole({ ...row.editRow, id: row.id })
        } catch (error) {
          this.$message.warning(error)
          return
        }
        this.$message.success('更新角色成功')
        // 更新显示数据  退出编辑状态
        Object.assign(row, {
          ...row.editRow,
          isEdit: false // 退出编辑模式
        })
      } else {
        this.$message.warning('角色和描述不能为空')
      }
    },
    // 编辑模式下 - 点击取消按钮
    btnEditChancel(row) {
      row.isEdit = false
    },
    // 删除角色
    async handleConfirm(id) {
      await delRole(id)
      // 如果删除的是本页最后一条数据
      if (this.roleList.length === 1) this.pageParams.page--
      this.$message.success('删除成功')
      this.getRoleList()
    },
    // 点击分配权限按钮
    async btnPermission(id) {
      this.currentRoleId = id
      const { permIds } = await getRoleDetail(id)
      console.log(permIds)
      this.permIds = permIds
      this.permissionData = dataConvertion(await getPermissionList(), 0)
      this.showPermissionDialog = true
    },
    // 分配权限 - 点击确认按钮
    async btnPermissionOK() {
      await assignPerm({
        id: this.currentRoleId,
        permIds: this.$refs.permTree.getCheckedKeys()
      })
      this.$message.success('角色分配权限成功')
      this.showPermissionDialog = false
    }
  }
}
</script>

<style lang="scss" scoped>
.role-operate {
  padding: 10px;
}
#delete {
  margin-left: 10px !important;
}
</style>
